package cn.tedu._04weibo.controller;

import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import cn.tedu._04weibo.mapper.UserMapper;
import cn.tedu._04weibo.pojo.dto.UserRegParam;
import cn.tedu._04weibo.pojo.entity.User;
import cn.tedu._04weibo.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@RestController
@Tag(name = "01-用户模块")
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 1.注册功能
     */
    @PostMapping("reg")
    @Operation(summary = "用户注册功能")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody UserRegParam userRegParam){
        log.debug("userRegParam = " + userRegParam);
        //校验用户名是否被占用
        String username = userRegParam.getUsername();
        int count = userMapper.selectByUsername(username);
        if (count > 0){ //被占用
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }
        // 未被占用
        User user = new User();
        BeanUtils.copyProperties(userRegParam, user);
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        return JsonResult.ok();
    }

    /**
     * 2.登录功能
     */
    @PostMapping("login")
    @Operation(summary = "用户登录功能")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserRegParam userRegParam, HttpSession session){
        log.debug("userRegParam = " + userRegParam);
        UserVO userVO = userMapper.selectByUsernameAndPassword(userRegParam);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user", userVO);

        return JsonResult.ok(userVO);
    }

    /**
     * 3.获取当前用户功能
     */
    @GetMapping("currentUser")
    @Operation(summary = "获取当前用户功能")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");

        return JsonResult.ok(userVO);
    }

    /**
     * 4.退出登录功能
     */
    @GetMapping("logout")
    @Operation(summary = "退出登录功能")
    @ApiOperationSupport(order = 40)
    public JsonResult logout(HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok();
    }
}
